package com.yuzi.common;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.cron4j.Cron4jPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;
import com.yuzi.controller.mobileCon.MobController;
import com.yuzi.controller.popularizeCon.*;
import com.yuzi.controller.systemCon.*;
import com.yuzi.handler.HtmSkipHandler;
import com.yuzi.interceptor.ExceptionInterceptor;
import com.yuzi.model.popularizeMo.*;
import com.yuzi.model.systemMo.*;
import com.yuzi.model.telMo.TelCustomer;
import com.yuzi.model.telMo.TelCustomerCollection;
import com.yuzi.model.telMo.TelCustomerLoginHistory;
import com.yuzi.service.popularizeSer.CuItemTodayConfigService;
import com.yuzi.share.AuthKit;
import com.yuzi.utils.kit.RemoveDruidAdHandle;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

public class BaseConfig extends JFinalConfig {

    public void configConstant(Constants constants) {
        PropKit.use("jConfig.properties");
        Boolean isDev = PropKit.getBoolean("isDev");
        String baseUploadPath = PropKit.get("baseUploadPath");
        constants.setDevMode(isDev);
        constants.setEncoding("utf-8");
        constants.setBaseUploadPath(baseUploadPath);
        /*
        //此处已经用shiro替代
        constants.setError401View("/common/404.html");
        constants.setError403View("/common/404.html");
        constants.setError404View("/common/404.html");
        constants.setError500View("/common/404.html");
        */
    }

    public void configRoute(Routes routes) {
        //String baseViewPath = PropKit.use("jConfig.properties").get("baseViewPath");
        routes.add("/",MobController.class);
        routes.add("/index",HomeController.class);
        routes.add("/login_",LoginController.class);

        routes.add("/admin/index",IndexController.class);
        routes.add("/admin/home",HomeController.class);
        routes.add("/admin/systemCategory",MenuController.class);
        routes.add("/admin/userList",UserController.class);
        routes.add("/admin/roleList",RoleController.class);
        routes.add("/admin/roleAuth",RoleAuthController.class);
        routes.add("/admin/dictList",DictController.class);
        routes.add("/admin/buttonList",ButtonController.class);

        //popularize
        routes.add("/popluarize/cugroupList",CuGroupController.class);
        routes.add("/popluarize/cuitemList",CuItemController.class);
        routes.add("/popluarize/cuitemtodayList",CuItemTodayController.class);
        routes.add("/popluarize/cuitemtodayConfig",CuItemTodayConfigController.class);
        routes.add("/popluarize/cugiAsso",CuGIAssoController.class);
        routes.add("/popluarize/cuflashList",CuFlashController.class);
        routes.add("/popluarize/plugin",PluginAiringController.class);

        //mobile
        routes.add("/mobile/productList",MobController.class);
    }

    public void configEngine(Engine engine) {
        engine.addSharedObject("ctx_path", JFinal.me().getContextPath());//配置这样一句

        //判断权限
        engine.addSharedObject("au",new AuthKit());

        engine.addSharedObject("application",JFinal.me().getServletContext());
    }

    public void configPlugin(Plugins plugins) {
        Prop p = PropKit.use("jConfig.properties");
        DruidPlugin dp = new DruidPlugin(p.get("jdbc.url"),p.get("jdbc.username"),p.get("jdbc.password"),p.get("jdbc.driverClassName"));


        // 1.统计信息插件
        StatFilter statFilter = new StatFilter();
        statFilter.setMergeSql(true);
        statFilter.setLogSlowSql(true);
        // 慢查询目前设置为1s,随着优化一步步进行慢慢更改
        statFilter.setSlowSqlMillis(Duration.ofMillis(1000).toMillis());
        dp.addFilter(statFilter);
        dp.setFilters("stat,wall");
        // 2.防注入插件
        WallFilter wall = new WallFilter();
        wall.setDbType("mysql");
        dp.addFilter(wall);

        plugins.add(dp);
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);

        arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
        arp.setShowSql(true);
        arp.getEngine().setSourceFactory(new ClassPathSourceFactory());
        arp.addSqlTemplate("all.sql");
        arp.addMapping("sys_user",SysUser.class);
        arp.addMapping("sys_menu",SysMenu.class);
        arp.addMapping("sys_role_menu",SysRoleMenu.class);
        arp.addMapping("sys_user_role",SysUserRole.class);
        arp.addMapping("sys_role",SysRole.class);
        arp.addMapping("sys_dict",SysDict.class);
        arp.addMapping("sys_button",SysButton.class);
        arp.addMapping("sys_role_menu_button",SysRoleMenuButton.class);

        arp.addMapping("cu_group",CuGroup.class);
        arp.addMapping("cu_item",CuItem.class);
        arp.addMapping("cu_item_today",CuItemToday.class);
        arp.addMapping("cu_item_today_config",CuItemTodayConfig.class);
        arp.addMapping("cu_group_item_asso",CuGroupItemAsso.class);
        arp.addMapping("cu_flash",CuFlash.class);

        arp.addMapping("tel_customer",TelCustomer.class);
        arp.addMapping("tel_customer_collection",TelCustomerCollection.class);
        arp.addMapping("tel_customer_loginhistory",TelCustomerLoginHistory.class);

        arp.addMapping("plugin_airing",PluginAiring.class);
        plugins.add(arp);

        plugins.add(new EhCachePlugin(PathKit.getRootClassPath()  + "/ehcache.xml"));

        plugins.add(new Cron4jPlugin(PropKit.use("task.properties")));

        //redis pvInfo pvStatistics uvStatistics 三个模块
        String redisServer = p.get("redis.server");
        int redisPort = p.getInt("redis.port");
        int redisTimeout = p.getInt("redis.timeout");
        RedisPlugin pvInfo = new RedisPlugin(Constant.RedisType.pvCacheName,redisServer,redisPort,redisTimeout);
        plugins.add(pvInfo);

    }

    public void configInterceptor(Interceptors interceptors) {
        interceptors.add(new SessionInViewInterceptor(true));
        //异常统一处理
        //全局拦截器，对所有请求拦截
        interceptors.add(new ExceptionInterceptor());

        //可以随处获取session，前提要走controller
        //interceptors.add(new SessionInterceptor());

    }

    public void configHandler(Handlers handlers) {
        //更改JFinal的web.xml 拦截后缀名
        handlers.add(new HtmSkipHandler());
        //Xss 攻击处理
        //handlers.add(new XssHandler());

        //删除阿里云广告代码
        handlers.add(new RemoveDruidAdHandle());
        //配置Druid 数据库统计
        DruidStatViewHandler statViewHandler = new DruidStatViewHandler("/druid", new IDruidStatViewAuth() {
            @Override
            public boolean isPermitted(HttpServletRequest request) {
                SysUser sysUser = (SysUser) request.getSession().getAttribute(Constant.SessionKey.userKey);
                if (sysUser == null){
                    return false;
                }
                return true;
            }
        });
        handlers.add(statViewHandler);
    }

    //项目启动开启一个线程
    @Override
    public void afterJFinalStart(){
        JFinal.me().getServletContext().setAttribute("itemTodayConfig",CuItemTodayConfigService.dao.findCuItemTodayConfig());
    }

    public static void main(String[] args) {
        UndertowServer.start(BaseConfig.class,80,true);
    }
}
